package com.hanxiaozhang.threadbase1ndedition.no98producerandconsumer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈使用堵塞队列实现生产者与消费者〉
 *
 * @author hanxinghua
 * @create 2021/11/12
 * @since 1.0.0
 */
public class No3UseBlockingQueue {


    public static void main(String[] args) throws InterruptedException {

        No3Platform platform = new No3Platform();

        // 生产者每10ms生成一个汉堡
        Thread producer = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                platform.increment();
            }
        }, "Producer");
        // 消费者每5ms消耗一个汉堡
        Thread consumer = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(15);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                platform.decrement();
            }
        }, "Consumer");

        producer.start();
        TimeUnit.MILLISECONDS.sleep(100);
        consumer.start();

    }

}

class No3Platform {

    private BlockingQueue<String> queue = new ArrayBlockingQueue(10);
  //  private BlockingQueue<String> queue = new LinkedBlockingQueue(10);

    /**
     * 自增
     */
    public synchronized void increment() {
        try {
            queue.put("hamburger");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("increment hamburger,current is " + queue.size());
    }


    /**
     * 自减
     */
    public synchronized void decrement() {
        try {
            queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("decrement hamburger,current is " + queue.size());
    }

}
